package com.guet.careapp.utils;

import java.lang.reflect.Field;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ClearSetUtil {
	/**
	 * 清空关联
	 * 
	 * @param clazz
	 * @param obj
	 */
	public static void clearSet(Class<?> clazz, Object obj) {
		Field[] fields = clazz.getDeclaredFields();
		Info.print(clazz.getName());
		for (Field field : fields) {
			if (field.getType().getName().equals("java.util.Set")) {
				try {
					Set<?> set = (Set<?>) field.get(obj);
					for (Object obj2 : set) {
						clearObject(obj2.getClass(), obj2, obj, clazz.getName());
					}
					Info.print(set.size());
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 删除指定对象的关联
	 * 
	 * @param clazz
	 * @param obj
	 * @param clearObj
	 * @param clearObjectName
	 */
	public static void clearObject(Class<?> clazz, Object obj, Object clearObj, String clearObjectName) {
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			if (field.getType().getName().equals("java.util.Set")) {
				String classFullyQualifiedName = getClassFullyQualifiedName(field.getGenericType().toString());
				if (classFullyQualifiedName.equals(clearObjectName)) {
					try {
						Set<?> set = (Set<?>) field.get(obj);
						set.remove(clearObj);
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 用正则获取set的T全限定名
	 * 
	 * @param str1
	 * @return
	 */
	public static String getClassFullyQualifiedName(String str1) {
		String result = null;
		Pattern pattern = Pattern.compile("<(.*?)>");
		Matcher matcher = pattern.matcher(str1);
		while (matcher.find()) {
			result = matcher.group(1);
		}
		return result;
	}
}
